package org.example.com.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.com.Bean.User;
import org.example.com.config.JwtConfig;
import org.example.com.exception.UserloginException;
import org.example.com.mapper.UserMapper;
import org.example.com.service.UserService;
import org.example.com.util.JsonResult;
import org.example.com.util.RecultTool;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService  {
    private final StringRedisTemplate stringRedisTemplate;

    public UserServiceImpl(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public JsonResult login(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());
        queryWrapper.eq("password", user.getPassword());
        queryWrapper.eq("status", 1);
        User one=getOne(queryWrapper);
        System.out.println("1."+one);
        if(one==null){
            throw new UserloginException("账号或者密码错误");
        }
        String token= JwtConfig.getJwtToken(one);
        ValueOperations<String,String> ops=stringRedisTemplate.opsForValue();
        // 判断该用户是否已经登陆
        Boolean hasKey = stringRedisTemplate.hasKey("front_token:" + one.getId());
        if (Boolean.TRUE.equals(hasKey)) {
            throw new UserloginException("该用户已经登陆！");
        }
        ops.set("front_token:" + one.getId(),token);
        return RecultTool.success(token);
    }

    @Override
    public JsonResult register(User user) {
        return null;
    }
}
